package systemController

import (
	"net/http"
	"wisdomCoach/global"
	"wisdomCoach/model"
	"wisdomCoach/utils"

	"github.com/gin-gonic/gin"
)

type LoginRequest struct {
	Code     string `json:"code"`
	Password string `json:"password"`
	Username string `json:"username"`
	Uuid     string `json:"uuid"`
}

func Login(cxt *gin.Context) {
	var (
		loginRequest LoginRequest
		user         model.User
	)
	if err := cxt.ShouldBindJSON(&loginRequest); err != nil {
		cxt.JSON(http.StatusBadRequest, gin.H{
			"msg": "请求数据格式有误",
		})
		return
	}

	if b := utils.VerifyCode(loginRequest.Code, loginRequest.Uuid); !b {
		cxt.JSON(http.StatusForbidden, gin.H{
			"error": "验证码错误",
		})
		return
	}

	if err := global.DB.Where("user_name = ?", loginRequest.Username).Find(&user).Error; err != nil {
		cxt.JSON(http.StatusForbidden, gin.H{
			"error": "用户名不存在",
		})
		return
	}

	if err := utils.DecryptionPassword(loginRequest.Password, user.Password); err != nil {
		cxt.JSON(http.StatusForbidden, gin.H{
			"error": "密码错误",
		})
		return
	}

	if err := global.DB.Where("user_name = ?", loginRequest.Username).First(&user).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}

	token, err := utils.CreateToken(user.UserId, user.UserName)
	if err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	cxt.JSON(http.StatusOK, gin.H{
		"code":  200,
		"token": token,
		"msg":   "操作成功",
	})
}
